Rails Ajax Examples (Without jQuery)
Introduction
Rails ships with turbolinks which:
automatically fetches the page, swaps in its
<body>
, and merges its<head>
, all without incurring the cost of a full page load.
This creates a reactive, fast application. However, there are times when turbolinks
is not enough, and you’ll want to roll your own AJAX solutions.
Blueprint
Below is a generic blueprint to follow when implementing AJAX on the create
action of a model in a Rails application.
1: Controller
Create a respond_to
block and make sure to pass format.js
in the block. This will automatically render a corresponding create.js.erb
file. This file needs to be manually created in the corresponding views
directory.
2: Form
Make sure your form does not use local: true
. Otherwise, the form will not submit remotely.
3: Create View
Handle errors and successful model creations with Javascript in your corresponding app/views/your_model/create.js.erb
file. Note that any ruby
code will get evaluated first. This means that you still have access helpful Rails layout and rendering methods, such as Partials.
Example 1: Dynamically Add a New Comment to a List of Comments with Ajax
In this scenario you want to post a new comment
to a list of existing comments
asynchronously.
Create View
Example 2: Dynamically Add a New Author to a Select List of Existing Authors
In this scenario you want to create a new author
while adding or editing an existing post
that relies on a relationship with an author
.